﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;
using System.Diagnostics;
using com.drsofts.age.pluginsdk.utils;

namespace com.drsofts.age.pluginsdk.dal
{
    public abstract class DataAccess<T>
    {
        private String _connectionString;
        protected String ConnectionString
        {
            get { return this._connectionString; }
            set { this._connectionString = value; }
        }

        protected int ExecuteNonQuery(DbCommand cmd)
        {
            if (cmd.Connection.State == ConnectionState.Closed) cmd.Connection.Open();
            int res = cmd.ExecuteNonQuery();
            return res;
        }

        protected IDataReader ExecuteReader(DbCommand cmd)
        {
            if (cmd.Connection.State == ConnectionState.Closed) cmd.Connection.Open();
            return ExecuteReader(cmd, CommandBehavior.Default);
        }
        protected IDataReader ExecuteReader(DbCommand cmd, CommandBehavior behavior)
        {
            if (cmd.Connection.State == ConnectionState.Closed) cmd.Connection.Open();
            return cmd.ExecuteReader(behavior);
        }

        protected object ExecuteScalar(DbCommand cmd)
        {
            if (cmd.Connection.State == ConnectionState.Closed) cmd.Connection.Open();
            return cmd.ExecuteScalar();
        }

   
        //
        //implémente le design pattern Instance et retourne une instance unique de la classe actuelle
        //

        private static T _instance;
        static public T Instance
        {
            get {
                if (_instance == null)
                {
                    _instance = Activator.CreateInstance<T>();
                }
                return _instance;
            }
        }

        public DataAccess()
        {
            this._connectionString = (String)System.Web.HttpContext.Current.Application["DefaultConnectionString"];
        }

        public abstract Object GetObjectFromReader(IDataReader reader,bool close);
        public abstract List<Object> GetObjectsFromReader(IDataReader reader);
        public abstract long PerformInsert(Object objet);
        public abstract bool PerformUpdate(Object objet);
        public abstract bool PerformDelete(long id, out bool isRefereced);
    }
}
